<template>
  <div class="app-container">
    <div class="table-box">
      <!-- 按钮功能区 开始 -->
      <el-row :gutter="10" class="btn-box">
        <el-col
          :xs="24"
          :sm="24"
          :md="24"
          :lg="24"
          :xl="24"
          class="btnfunction-section-col"
        >
          <el-button-group>
            <el-button type="primary" icon="el-icon-plus" :disabled="!checkPermission(['admin.permission.store'])" @click="handleCreate()">{{
              $t('common.create')
            }}</el-button>
            <el-button type="primary" :loading="patchStoreLoading" icon="el-icon-more" :title="$t('common.patch_create')" :disabled="!checkPermission(['admin.permission.patchStore'])" @click="handlePatchStore()" />
          </el-button-group>
          <el-button type="primary" icon="awesome-icon fas fa-sort" :disabled="!checkPermission(['admin.permission.updateSort'])" @click="handleUpdateSort()">
            {{ $t('common.updateSort') }}
          </el-button>
          <el-button-group>
            <el-button
              icon="el-icon-sort"
              :title="$t('common.updown')"
              @click="handleUpDown()"
            >{{
              $t('common.updown')
            }}</el-button>
          </el-button-group>
          <el-button icon="el-icon-refresh" @click="handleRefresh">{{
            $t('common.refresh')
          }}</el-button>
        </el-col>
      </el-row>
      <!-- 按钮功能区 结束 -->

      <!-- Note that row-key is necessary to get a correct row order.   table当前行高亮属性highlight-current-row-->
      <el-table
        ref="treeTable"
        v-loading="listLoading"
        :data="list"
        row-key="id"
        border
        fit
        highlight-current-row
        :default-expand-all="isExpand"
        style="width: 100%"
        :indent="16"
        @selection-change="handleSelectionChange"
        @select-all="selectAll"
      >
        <el-table-column type="selection" align="center" fixed="left" />
        <el-table-column
          align="center"
          label="ID"
          type=""
          width="110"
        >
          <template slot-scope="{ row }">
            <span>{{ row.id }}</span>
          </template>
        </el-table-column>

        <el-table-column
          align="left"
          :label="$t('permission.name')"
          class-name="menuIcon"
          min-width="200px"
        >
          <template slot-scope="{ row }">
            <span>{{ row.name }}</span>
          </template>
        </el-table-column>

        <el-table-column
          :label="$t('common.type')"
          class-name="status-col"
          width="90"
          align="center"
        >
          <template slot-scope="{ row }">
            <el-tag :type="row.type==1?'info':''">
              <span> {{ row.type | paraseDictionaryItemName('permissionTypeVar') }}</span>
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          :label="$t('permission.public_type')"
          width="120"
          align="center"
        >
          <template slot="header">
            <span> {{ $t('permission.public_type') }} </span>
            <el-tooltip class="item" effect="dark" placement="right">
              <div
                slot="content"
                v-html="$t('permission.table_header_public_type_tips')"
              />
              <i class="awesome-icon fas fa-question-circle" />
            </el-tooltip>
          </template>
          <template slot-scope="{ row }">
            <el-tag v-if="row.type==2 && row.public_type!=0">
              <span>{{ row.public_type | paraseDictionaryItemName('permissionPublicTypeVar') }}</span>
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column align="center" min-width="150px">
          <template slot="header">
            <span> {{ $t('permission.priv') }} </span>
            <el-tooltip class="item" effect="dark" placement="right">
              <div
                slot="content"
                v-html="$t('permission.table_header_permission_tips')"
              />
              <i class="awesome-icon fas fa-question-circle" />
            </el-tooltip>
          </template>
          <template slot-scope="{ row }">
            <span v-if="row.priv" class="link-type" :title="$t('common.click_copy')" @click="clipboard(`v-permission=&quot;['${row.priv}']&quot;`, $event)" v-text="row.priv" />
            <span v-else class="link-type" v-text="'-'" />
          </template>
        </el-table-column>

        <el-table-column width="180" :label="$t('common.sort')" align="center">
          <template slot-scope="{ row }">
            <el-input-number v-model="row.sort" controls-position="right" :min="1" />
          </template>
        </el-table-column>

        <el-table-column
          :label="$t('common.created_at')"
          width="200"
          align="center"
        >
          <template slot-scope="{ row }">
            <span>{{ row.created_at }}</span>
          </template>
        </el-table-column>

        <el-table-column
          :label="$t('common.operation')"
          align="center"
          class-name="small-padding fixed-width"
          width="150"
          fixed="right"
        >
          <template slot-scope="{ row, $index }">
            <el-link
              type="primary"
              :underline="false"
              :disabled="!checkPermission(['admin.permission.update'])&&!checkPermission(['admin.permission.show'])"
              icon="el-icon-edit"
              :title="$t('common.edit')"
              @click="handleEdit(row)"
            >{{ $t('common.edit') }}
            </el-link>&nbsp;
            <el-link
              type="primary"
              :underline="false"
              :disabled="!checkPermission(['admin.permission.destroy'])"
              icon="el-icon-delete"
              :title="$t('common.delete')"
              @click="handleDelete(row, $index)"
            >{{ $t('common.delete') }}
            </el-link>&nbsp;
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加/修改 开始 -->
    <el-dialog
      :title="editType?$t('common.edit'):$t('common.create')"
      :visible.sync="dialogFormVisible"
      :before-close="handleResetDialog"
      custom-class="jsp-dialog-modal-box"
    >

      <el-form
        ref="editForm"
        :rules="editRules"
        :model="editForm"
        class="editform"
        label-width="100px"
      >

        <el-form-item prop="type">
          <span slot="label">
            {{ $t('common.type') }}
          </span>
          <el-radio-group v-model="editForm.type" :disabled="editForm.id>0">
            <el-radio v-for="item in dictionaryService.getItems('permissionTypeVar')" :key="item.id" :label="Number(item.value)">{{ item.name }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          v-show="editForm.type==2"
          :label="$t('permission.public_type')"
          prop="public_type"
        >

          <span slot="label">
            <el-tooltip class="item" effect="dark" placement="right">
              <div slot="content" v-html="$t('permission.table_header_public_type_tips')" />
              <i class="awesome-icon fas fa-question-circle" />
            </el-tooltip>
            {{ $t('permission.public_type') }}
          </span>

          <el-radio-group v-model.number="editForm.public_type">
            <el-radio v-for="item in dictionaryService.getItems('permissionPublicTypeVar')" :key="item.id" :label="Number(item.value)">{{ item.name }}</el-radio>
          </el-radio-group>

        </el-form-item>

        <!-- 权限名称 -->
        <el-form-item :label="$t('permission.name')" prop="name">
          <el-input
            v-model="editForm.name"
            :placeholder="$t('permission.name_tips')"
            clearable
          />
        </el-form-item>

        <!-- 所属模块 -->
        <el-form-item
          v-show="editForm.type==1"
          prop="controller"
          :label="$t('permission.controller')"
          :rules="editForm.type==1?editRules.controller:[{required:false}]"
        >
          <el-select v-model="editForm.controller" filterable :placeholder="$t('permission.controller_tips')" class="module" clearable>
            <el-option
              v-for="(item, key) in controller_list"
              :key="key"
              :label="item.controller"
              :value="item.controller"
              :disabled="item.disabled"
            />
          </el-select>
        </el-form-item>

        <!-- 所属权限 -->
        <el-form-item
          v-show="editForm.type==2"
          prop="priv"
          :label="$t('permission.priv')"
          :rules="editForm.type==2?editRules.priv:[{required:false}]"
        >
          <el-select v-model="editForm.priv" filterable :placeholder="$t('permission.priv_tips')" class="module" clearable>
            <el-option
              v-for="(item, key) in priv_list"
              :key="key"
              :label="item.name"
              :value="item.name"
              :disabled="item.disabled"
            />
          </el-select>
        </el-form-item>

        <!-- 描述 -->
        <el-form-item
          :label="$t('permission.description')"
          prop="description"
        >
          <el-input
            v-model="editForm.description"
            type="textarea"
            :placeholder="$t('permission.description_tips')"
          />
        </el-form-item>

        <!-- 排序 -->
        <el-form-item
          :label="$t('common.sort')"
          prop="sort"
        >
          <el-input-number v-model="editForm.sort" controls-position="right" :min="1" :placeholder="$t('common.sort_tips')" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancelEdit">
          {{ $t('common.cancel') }}
        </el-button>
        <el-button
          type="primary"
          :loading="submitLoading || editFormLoad"
          :disabled="editType&&!checkPermission(['admin.permission.update']) || !editType&&!checkPermission(['admin.permission.store'])"
          @click="submit(editForm.id)"
        >
          {{ editFormLoad? $t('common.loading'): $t('common.submit') }}
        </el-button>
      </div>
    </el-dialog>
    <!-- 添加/修改 开始 -->

  </div>
</template>

<script>
import { index, store, update, destory, updateSort, show as getPermissionDetail, patchStore } from '@/api/permission'
import { treeToFlat } from '@/utils/tree'
import { getPermissionRouteConfig } from '@/api/route'
import clipboard from '@/utils/clipboard'
import checkPermission from '@/utils/permission'

export default {
  name: 'PermissionIndex',
  data() {
    return {
      tableKey: 0,
      list: [],
      listQuery: {
        sort: '+sort'
      },
      flatList: [],
      listLoading: true,
      multipleSelection: [],
      isSelected: false,
      editType: 0,
      dialogFormVisible: false,
      submitLoading: false,
      editFormLoad: false,
      isExpand: false,
      patchStoreLoading: false,
      editForm: {
        id: 0,
        type: 2,
        name: '',
        controller: '',
        priv: '',
        public_type: 0,
        description: '',
        sort: 999
      },
      editRules: {
        name: [
          { required: true, min: 2, max: 30, message: this.$t('permission.name_tips') },
          { message: this.$t('permission.name_length_tips') }
        ],
        controller: [
          { required: true, message: this.$t('permission.controller_tips'), trigger: ['change', 'blur'] }
        ],
        priv: [
          { required: true, message: this.$t('permission.priv_tips'), trigger: ['change', 'blur'] }
        ]
      },
      controller_list: [],
      priv_list: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    checkPermission,
    clipboard,
    async getList() {
      this.listLoading = true
      await index(this.listQuery).then((response) => {
        const { items, total } = response.data
        this.total = total
        this.flatList = treeToFlat(items)
        this.list = items
        this.listLoading = false
      }).catch(() => {
        this.closeBack()
      })
      this.getPriv()
    },
    getPriv() {
      // 权限
      getPermissionRouteConfig().then((response) => {
        const { module, permission } = response.data
        this.priv_list = permission
        this.controller_list = module
      }).catch(() => {})
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    selectAll(selection) {
      this.isSelected = !this.isSelected
      this.flatList.forEach((row, index) => {
        this.$refs.treeTable.toggleRowSelection(row, this.isSelected)
      })
    },
    handleDelete(row, index) {
      this.$confirm(this.$t('common.delete_confirm_tips'), {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning'
      })
        .then(() => {
          destory(row.id).then((response) => {
            this.$message.success(response.message)
            this.getList()
          }).catch(() => {
          })
        })
        .catch(() => {
          this.$message.info(this.$t('common.canceled'))
        })
    },
    handleUpdateSort() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning(this.$t('common.please_choose_sort_tips'))
        return
      }
      const params = this.multipleSelection.map((row, index) => {
        return { id: row.id, sort: row.sort }
      })
      updateSort({ sort: params }).then((response) => {
        this.$message.success(response.message)
        this.getList()
      }).catch(() => {
      })
    },
    handleCreate() {
      this.editType = 0
      this.dialogFormVisible = true
    },
    handleEdit(row) {
      this.editFormLoad = true
      this.editType = 1
      this.dialogFormVisible = true
      getPermissionDetail(row.id).then((response) => {
        this.editForm = response.data
        this.editFormLoad = false
      }).catch(() => {})
    },
    // 添加/添加权限
    submit(id) {
      this.$refs['editForm'].validate(async(valid) => {
        if (valid) {
          this.submitLoading = true
          let response
          if (id > 0) {
            response = await update(id, this.editForm).catch(() => {})
          } else {
            response = await store(this.editForm).catch(() => {})
          }
          this.submitLoading = false
          if (response instanceof Object) {
            this.$message.success(response.message)
            this.handleResetDialog()
            this.getList()
          }
        } else {
          this.$message.error(this.$t('common.pleaseFillRequired'))
        }
      })
    },
    handleCancelEdit() {
      this.handleResetDialog()
    },
    handleResetDialog() {
      this.$refs['editForm'].resetFields()
      this.dialogFormVisible = false
      this.submitLoading = false
    },
    downUpData(data, isExpand) {
      data.forEach((i) => {
        if (i.children) {
          this.$refs.treeTable.toggleRowExpansion(i, isExpand)
          this.downUpData(i.children, isExpand)
        }
      })
    },
    handleUpDown() {
      this.isExpand = !this.isExpand
      this.downUpData(this.list, this.isExpand)
    },
    handleRefresh() {
      this.getList()
    },
    handlePatchStore() {
      this.$confirm(this.$t('permission.patch_create_tips'), this.$t('common.warm_tips'), {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning'
      }).then(() => {
        this.patchStoreLoading = true
        patchStore().then((response) => {
          this.$message.success(response.message)
          this.getList()
          this.patchStoreLoading = false
        }).catch(() => {
          this.patchStoreLoading = false
        })
      })
        .catch(() => {
          this.$message.info(this.$t('common.canceled'))
        })
    }
  }
}
</script>

<style scoped type="scss">
.module {
  width:100%
}
</style>

